package com.core.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.system.dao.SystemPermissionMapper;
import com.core.system.service.ISystemPermissionService;
import com.core.system.service.ISystemRoleService;
import com.pojo.entity.SystemPermissionEntity;
import com.pojo.dto.SystemPermissionDto;
import com.pojo.dto.SystemRoleDto;
import com.pojo.req.permission.PagePermissionReq;
import com.pojo.req.permission.TemplatePermissionReq;
import com.pojo.resp.permission.PagePermissionResp;
import com.utility.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统权限表  服务实现类
 * </p>
 *
 * @author hewei
 * @since 2020-12-19
 */
@Service
public class SystemPermissionServiceImpl extends ServiceImpl<SystemPermissionMapper, SystemPermissionEntity> implements ISystemPermissionService {

    @Autowired
    private ISystemRoleService roleService;

    @Autowired
    private CommonService commonService;

    /**
     * 根据 templateId 查询关联的数据权限
     *
     * @param templateId
     * @return
     */
    public List<SystemPermissionEntity> getPermissionList(Long templateId) {
        LambdaQueryWrapper<SystemPermissionEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemPermissionEntity::getIsDelete, Constant.ZERO);
        if (!Objects.isNull(templateId)) {
            queryWrapper.eq(SystemPermissionEntity::getTemplateId, templateId);
        }
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询所有未删除的权限
     *
     * @return
     */
    public List<SystemPermissionEntity> getPermissionList() {
        return getPermissionList(null);
    }



    @Override
    public IPage<PagePermissionResp> page(PagePermissionReq permission) {
        return this.baseMapper.permissionPage(new Page<>(permission.getCurrentPage(), permission.getPageSize()), permission);
    }

    /**
     *  根据用户角色查询操作权限
     * @param templatePermissionReq 角色id
     * @return
     */
    @Override
    public List<SystemPermissionDto> selectRolePermission(TemplatePermissionReq templatePermissionReq) {
        List<SystemRoleDto> role = roleService.getRole(commonService.getUserName());
        List<Long> collect = role.stream().map(SystemRoleDto::getId).collect(Collectors.toList());
        return this.baseMapper.selectRolePermission(collect,templatePermissionReq.getTemplateId());
    }
}
